<template>
  <common-layout>
    <div class="signUp" v-if="signFlag">
      <a-row class="see_row" style="width:100%;">
        <a-form-model ref="ruleForm" class="ant-advanced-form" :model="data" :rules="rules"
          :labelCol="{ style:'width:108px,color:#2a868e' }">
          <div class="colTitle">学生基本信息</div>
          <a-col class="borderCol">
            <a-form-model-item label="姓名" prop="name" class="form-w-95">
              <a-input class="baseCol" v-model="data.name" :maxLength="15" placeholder="请输入姓名" />
            </a-form-model-item>
          </a-col>
          <a-col class="borderCol">
            <a-form-model-item label="性别" prop="sex" class="form-w-95">
              <a-select placeholder="请选择性别" class="baseCol" v-model="data.sex">
                <a-select-option :value="1">男</a-select-option>
                <a-select-option :value="2">女</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col class="borderCol">
            <a-form-model-item label="证件类型" prop="cardType" class="form-w-95">
              <a-select v-model="data.cardType" placeholder="请选择证件类型" class="baseCol">
                <a-select-option :value="1">身份证</a-select-option>
                <a-select-option :value="2">护照</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col class="borderCol">
            <a-form-model-item label="证件号码" prop="cardId" class="form-w-95" >
              <a-input class="baseCol" v-model.trim="data.cardId" placeholder="请输入证件号码" />
            </a-form-model-item>
          </a-col>
          <div class="colTitle">报考基本信息</div>
          <a-col class="borderCol">
            <a-form-model-item label="报名批次" prop="registerBatch" class="form-w-95">
              <a-select class="baseCol" placeholder="请选择报名批次" allowClear v-model="data.registerBatch">
                <a-select-option v-for="(item, i) in piciList" :key="i" :value="+item.id">{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col class="borderCol">
            <a-form-model-item label="报名院校" prop="registerSchool" class="form-w-95">
              <a-select class="baseCol" placeholder="请选择报名院校" allowClear v-model="data.registerSchool">
                <a-select-option v-for="(item, i) in xiaoList" :key="i" :value="item.id">{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col class="borderCol">
            <a-form-model-item label="所报层次" prop="registerLevel" class="form-w-95">
              <a-select class="baseCol" placeholder="请选择所报层次" allowClear v-model="data.registerLevel">
                <a-select-option :value="1">专升本</a-select-option>
                <a-select-option :value="2">高起专</a-select-option>
                <a-select-option :value="3">高起本</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col class="borderCol">
            <a-form-model-item label="所报专业" prop="registerMajor" class="form-w-95" :colon="false">
              <a-input class="baseCol" :maxLength="15" v-model.trim="data.registerMajor" placeholder="请输入所报专业" />
            </a-form-model-item>
          </a-col>
          <a-col class="borderCol">
            <a-form-model-item label="学习形式" prop="studyType" class="form-w-95">
              <a-select class="baseCol" placeholder="请选择学习形式" allowClear v-model="data.studyType">
                <a-select-option :value="1">网络教育</a-select-option>
                <a-select-option :value="2">成人教育</a-select-option>
                <a-select-option :value="3">开放教育</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col class="borderCol">
            <a-form-model-item label="学生状态" prop="studentStatus" class="form-w-95">
              <a-select class="baseCol" placeholder="请选择学生状态" allowClear v-model="data.studentStatus">
                <a-select-option :value="1">在读</a-select-option>
                <a-select-option :value="2">退学</a-select-option>
                <a-select-option :value="3">休学</a-select-option>
                <a-select-option :value="4">预报名</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <div class="colTitle">上传材料</div>
          <a-col class="borderColHeight">
            <a-form-model-item label="上传正反面身份证" prop="attachmentId" :labelCol="{ style: 'width:140px' }">
              <a-upload :accept="imageAccept" :action="uploadUrl" list-type="picture-card"
              :file-list="vipImgs" @preview="uploadImgPreview" :headers="uploadHead"
              @change="uploadImgChange">
                <div v-if="vipImgs.length < 1">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">上传图片</div>
                </div>
              </a-upload>
            </a-form-model-item>
          </a-col>
          <div class="colTitle">联系方式</div>
          <a-col class="borderCol">
            <a-form-model-item label="手机" prop="phone" class="form-w-95" :colon="false">
              <a-input class="baseCol" v-model.trim="data.phone" placeholder="请输入手机号" />
            </a-form-model-item>
          </a-col>
          <a-col class="borderCol">
            <a-form-model-item label="Email" prop="email" class="form-w-95" :colon="false">
              <a-input class="baseCol" v-model.trim="data.email" placeholder="请输入Email号" />
            </a-form-model-item>
          </a-col>
          <a-col class="borderCol">
            <a-form-model-item label="联系地址" prop="address" class="form-w-95" :colon="false">
              <a-input class="baseCol" v-model.trim="data.address" placeholder="请输入联系地址" />
            </a-form-model-item>
          </a-col>
          <a-col class="borderCol">
            <a-form-model-item label="联系电话" prop="connectPhone" class="form-w-95" :colon="false">
              <a-input class="baseCol" v-model.trim="data.connectPhone" placeholder="请输入联系电话" />
            </a-form-model-item>
          </a-col>
          <a-col class="borderCol" style="border-bottom:none">
            <div style="width:100%;text-align:center;">
              <a-button type="primary" @click="save">保存</a-button>
              <a-button style="margin-left:20px;" @click="goback">返回</a-button>
            </div>
          </a-col>
        </a-form-model>
      </a-row>
    </div>
    <div class="login" v-else>
      <a-form @submit="onSubmit" :form="form">
        <div class="logo">
          <img src="../../assets/img/logo.png" />
        </div>
        <div class="welcome">{{ systemName }}</div>
        <a-alert type="error" v-show="error" :message="error" showIcon style="margin-bottom: 24px;" />
        <a-form-item>
          <a-input autocomplete="autocomplete" size="large" placeholder="账号"
            v-decorator="['username', { rules: [{ required: true, message: '请输入账号', whitespace: true }] }]">
            <a-icon slot="prefix" type="user" />
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-input size="large" placeholder="密码" autocomplete="autocomplete" type="password" :maxLength="16"
            v-decorator="['password', { rules: [{ required: true, message: '请输入密码', whitespace: true }] }]">
            <a-icon slot="prefix" type="lock" />
          </a-input>
        </a-form-item>
        <!-- <a-form-item>
          <a-row :gutter="8" style="margin: 0 -4px">
            <a-col :span="16">
              <a-input size="large" placeholder="验证码"
                v-decorator="['securityCode', { rules: [{ required: true, message: '请输入验证码', whitespace: true }] }]"
                :maxLength="4" @pressEnter="onSubmit">
                <a-icon slot="prefix" type="safety" />
              </a-input>
            </a-col>
            <a-col :span="8" style="padding-left: 4px">
              <img @click="getVerifCode" ref="img" style="cursor:pointer;width: 100%;height: 36px;border-radius: 3px;">
            </a-col>
          </a-row>
        </a-form-item> -->
        <a-form-item>
          <a-checkbox :checked="remember" @change="rememberChange">记住密码</a-checkbox>
          <!-- <a-button type="link" style="float: right" @click="forgotPassWord">找回密码</a-button> -->
          <a-button :loading="logging" style="width: 100%;" size="large" htmlType="submit" type="primary">登录</a-button>
          <!-- <a-button :loading="logging" style="width:100%;background:#eb8200;border-color:#eb8200;margin-top:18px" size="large" type="primary" @click="onSign">填写报名表</a-button> -->
        </a-form-item>
      </a-form>
      <!-- <VerificationCodeInput ref="code" /> -->
      <Forgot ref="forgot" />
    </div>
  </common-layout>
</template>

<script>
import { setAuthorization, getAuthorizationHead } from '@/utils/request'
import { loadRoutes } from '@/utils/routerUtil'
import { debounce } from '@/utils/debounce.js'
import { authorityMapToMenu, authorityMapToPermissions } from '@/utils/loginUtil'
import { mapMutations, mapGetters } from 'vuex'
import CommonLayout from '@/layouts/CommonLayout'
// import VerificationCodeInput from '@/components/verification-code-input'
import Forgot from './Forgot'
import { login, getLoginVerifCode } from '@/services/user'
import { imageAccept } from '@/utils/options.js'
import { getBase64 } from '@/utils/util.js'
import { uploadImg } from '@/services/sys'
const BASE_URL = process.env.VUE_APP_API_URL
export default {
  name: 'Login',
  components: { CommonLayout, Forgot },
  computed: {
    ...mapGetters('setting', ['account']),
    systemName () {
      return this.$store.state.setting.systemName
    }
  },
  methods: {
    ...mapMutations('account', ['setUser', 'setPermissions', 'setRoles', 'setMenus', 'setLockPwd']),
    ...mapMutations('setting', ['setAccount']),
    // 预览图片
    async uploadImgPreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.preview.image = file.url || file.preview
      this.preview.visible = true
    },
    // 点击填写报名
    onSign () {
      this.signFlag = true
    },
    // 上传图片相关
    uploadImgChange ({ fileList }) {
      this.vipImgs = fileList.filter(f =>
        imageAccept.split(',').includes(f.type)
      )
      for (let i = 0; i < this.vipImgs.length; i++) {
        const d = this.vipImgs[i]
        if (d.status === 'done' && Object.hasOwnProperty.call(d, 'response')) {
          if (d.response.isSuccess) {
            this.vipImgs.splice(i, 1, {
              name: d.name,
              status: d.status,
              type: d.type,
              uid: d.uid,
              id: d.response.data.data.id,
              validFlag: d.response.data.data.validFlag,
              url: d.response.data.data.url
            })
            this.params.attachmentId = this.vipImgs[0].id
          } else {
            this.vipImgs.splice(i, 1)
            this.params.attachmentId = this.vipImgs[0].id
            this.$message.newFun(d.response.msg, 'error', 3)
          }
        }
      }
      console.log(this.vipImgs, '==')
    },
    // 保存
    save () {
      this.signFlag = false
    },
    // 返回
    goback () {
      this.signFlag = false
    },
    onSubmit (e) {
      debounce(() => {
        e.preventDefault()
        this.form.validateFields((err) => {
          if (!err) {
            this.logging = true
            const username = this.form.getFieldValue('username')
            const password = this.form.getFieldValue('password')
            // const securityCode = this.form.getFieldValue('securityCode')
            login(username, password)
              .then(this.afterLogin)
          }
        })
      })
    },
    afterLogin (res) {
      const loginRes = res
      console.log(loginRes, 'loginRes')
      if (loginRes.status === 200) { // 登录成功roleName
        // const { userId, userName, img, roleId, roleType, menus, roleCode } = loginRes.data
        const { menus } = loginRes.data
        const authorityMenus = authorityMapToMenu(menus)
        const authorityPermissions = authorityMapToPermissions(menus)
        localStorage.setItem('userName', loginRes.data.userName)
        localStorage.setItem('userId', loginRes.data.userId)
        // localStorage.setItem('userInfo', JSON.stringify(loginRes.data))
        // this.setUser({ id: userId, code: this.form.getFieldValue('name'), name: userName, avatar: img, address: '@CITY', position: '@POSITION', roleCode: roleCode })
        this.setPermissions(authorityPermissions)
        this.setMenus(authorityMenus)
        // this.setRoles({ id: roleId, type: String(roleType), name: userName, operation: [] })
        // this.setLockPwd(this.form.getFieldValue('password'))
        setAuthorization({ token: loginRes.data.token, expireAt: new Date(loginRes.data.expireAt) })
        if (this.remember) {
          this.setAccount({
            username: this.form.getFieldValue('username'),
            pwd: this.form.getFieldValue('password')
          })
        }
        // 获取路由配置
        loadRoutes()
        this.$router.push('/home')
        console.log(this.form.getFieldValue('username'), '登录成功')
        this.$message.newFun(this.form.getFieldValue('username') + '，欢迎回来', 'success', 3)
        this.logging = false
      } else if (loginRes.data) { // 第一次登录，验证手机号
        this.logging = false
        this.$message.newFun(loginRes.msg, 'error', 3)
        // this.$refs.code.open(this.form.getFieldValue('username'))
      } else { // 登录失败
        this.logging = false
        this.error = loginRes.msg
        // this.getVerifCode()
        this.$message.newFun(loginRes.message, 'error', 2)
      }
    },
    async getVerifCode () {
      const res = await getLoginVerifCode()
      const { isSuccess, data: response, msg } = res
      if (isSuccess) {
        this.$refs.img.src = 'data:image/png;base64,' + response.imgStr
        this.key = response.key
      } else {
        this.$message.newFun(msg, 'error', 2)
      }
      if (this.timeId) {
        clearTimeout(this.timeId)
        this.timeId = undefined
      }
      this.timeId = setTimeout(() => {
        this.getVerifCode()
      }, 60000)
    },
    rememberChange (e) {
      this.remember = e.target.checked
      if (!this.remember) {
        this.setAccount({})
      }
    },
    forgotPassWord () {
      this.$refs.forgot.open()
    }
  },
  destroyed () {
    if (this.timeId) {
      clearTimeout(this.timeId)
      this.timeId = undefined
    }
  },
  mounted () {
    // logout()
    this.remember = this.account instanceof Object && Object.hasOwnProperty.call(this.account, 'name')
    if (this.remember) {
      const { name, pwd } = this.account
      this.form.setFieldsValue({ name: name, password: pwd })
    }
  },
  async created () {
    // this.getVerifCode()
    this.uploadImageUrl = `${BASE_URL}/member/admin/base/member/level/upload`
    this.uploadHead = getAuthorizationHead()
  },
  data () {
    return {
      logging: false,
      error: '',
      form: this.$form.createForm(this),
      key: '',
      timeId: undefined,
      remember: false,
      signFlag: false,
      BASE_URL,
      uploadHead: '',
      imageAccept,
      uploadUrl: uploadImg(),
      vipImgs: [],
      data: {

      },
      piciList: [
        { id: '1', name: '2025春' },
        { id: '2', name: '2024秋' },
        { id: '3', name: '2024春' },
        { id: '4', name: '2023秋' },
        { id: '5', name: '2023春' },
        { id: '6', name: '2022秋' },
        { id: '7', name: '2022春' }
      ],
      xiaoList: [
        { id: '1', name: '北大' },
        { id: '2', name: '清华' },
        { id: '3', name: '上海交大' },
        { id: '4', name: '人民大学' },
        { id: '5', name: '农业大学' },
        { id: '6', name: '工业大学' },
        { id: '7', name: '航天航空大学' }
      ],
      rules: {
        name: [{ required: true, message: '请输入学生姓名', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        cardType: [{ required: true, message: '请选择设证件类型', trigger: 'change' }],
        cardId: [{ required: true, message: '请输入证件号码', trigger: 'blur' }],
        registerBatch: [{ required: true, message: '请选择报名批次', trigger: 'change' }],
        registerSchool: [{ required: true, message: '请选择报名院校', trigger: 'change' }],
        registerLevel: [{ required: true, message: '请选择所报层次', trigger: 'change' }],
        registerMajor: [{ required: true, message: '请输入所报专业', trigger: 'blur' }],
        studyType: [{ required: true, message: '请选择习形式', trigger: 'change' }],
        studentStatus: [{ required: true, message: '请选择学生状态', trigger: 'change' }],
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }]
      }
    }
  }
}
</script>

<style lang="less" scoped>
.common-layout {

  .login {
    width: 480px;
    height: 480px;
    background: #ffffff;
    padding: 50px 56px;
    position: fixed;
    right: 360px;

    @media screen and (max-width: 1680px) {
      right: 240px;
    }

    @media screen and (max-width: 1366px) {
      right: 120px;
    }

    // margin: 0 auto;
    @media screen and (max-width: 768px) {
      right: 60px;

      .welcome {
        // color: white;
        margin-top: 50px;
      }
    }

    @media screen and (max-width: 576px) {
      width: 95%;
      right: 2.4%;
    }

    @media screen and (max-width: 320px) {
      .captcha-button {
        font-size: 14px;
      }
    }

    .logo {
      margin-bottom: 16px;
      text-align: center;

      img {
        width: 50px;
        height: 50px;
      }
    }

    .welcome {
      margin-bottom: 60px;
      font-size: 28px;
      font-weight: 500;
      text-align: center;
      color: #333333;
      line-height: 40px;
    }

    .icon {
      font-size: 24px;
      color: @text-color-second;
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: @primary-color;
      }
    }
  }
  .signUp{
    width: 1190px;
    margin: 20px auto 0;
    min-height: 360px;
    border: 1px solid #d1d4d7;
    .colTitle{
      padding: 0 20px;
      box-sizing: border-box;
      height:50px;
      line-height:50px;
      background: #377cbd;
      color: #fff;
      border: 1px solid #377cbd;
    }
    .borderCol{
      height: 60px;
      padding-top: 14px;
      padding-right: 14px;
      margin-bottom: 0!important;
      border-bottom: 1px solid #d1d4d7;
    }
    .borderColHeight {
      height: 154px;
      padding-top: 14px;
      margin-bottom: 0!important;
      border-bottom: 1px solid #d1d4d7;
    }
  }
}
</style>
